package sample.com.wisdomhealth.wxapi;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.YangShengInfo.ReceiveDataInt;
import com.hyg.lib_common.DataModel.personal.LoginReceiveUserInfo;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.loginpart.LoginByCodeActivity;
import com.hyg.lib_common.loginpart.modle.WechatReceiveData;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import sample.com.wisdomhealth.R;
import sample.com.wisdomhealth.ui.MainActivity;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_w_x_entry);
        BaseApplication.api = WXAPIFactory.createWXAPI(this, "wxb16002f7defb77ce", true);
        BaseApplication.api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Log.i("lgb", "onReq: " + baseReq.openId);
    }

    @Override
    public void onResp(BaseResp baseResp) {
        Log.i("lgb", "onResp: ");
        //形参resp 有下面两个个属性比较重要
        //1.resp.errCode
        //2.resp.transaction则是在分享数据的时候手动指定的字符创,用来分辨是那次分享(参照4.中req.transaction)
        switch (baseResp.errCode) { //根据需要的情况进行处理
            case BaseResp.ErrCode.ERR_OK:
                Log.i("lgb", "onResp: 正确返回");
                String code = ((SendAuth.Resp) baseResp).code;
                Log.i("lgb", "onResp: " + code);
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=wxb16002f7defb77ce&secret=e59c9c70ab4f2564228befeb5f2b0128" +
                        "&code=" + code +
                        "&grant_type=authorization_code";
                CommonHttpUtil.getHttp(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Log.i("lgb", "onResponse:wexin "+result);
                        WechatReceiveData data = JSONObject.parseObject(result, WechatReceiveData.class);
                        wechatLogin(data.getOpenid());
                    }
                });
                //正确返回
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Log.i("lgb", "onResp: 用户取消");
                //用户取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Log.i("lgb", "onResp: 认证被否决");
                //认证被否决
                break;
            case BaseResp.ErrCode.ERR_SENT_FAILED:
                Log.i("lgb", "onResp: 发送失败");
                //发送失败
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                Log.i("lgb", "onResp: 不支持错误");
                //不支持错误
                break;
            case BaseResp.ErrCode.ERR_COMM:
                Log.i("lgb", "onResp: 一般错误");
                //一般错误
                break;
            default:
                //其他不可名状的情况
                break;
        }
    }

    public void wechatLogin(String openid) {
        CommonHttpUtil.loginWechat(openid, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(WXEntryActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse: " + result);
                ReceiveDataInt dataInt = JSONObject.parseObject(result, ReceiveDataInt.class);
                if (dataInt.getCode() == 200) {
                    LoginReceiveUserInfo userInfo=JSONObject.parseObject(dataInt.getData(),LoginReceiveUserInfo.class);
                    SharedPreferences.Editor editor=UserSPUtils.getUserInfoSp(WXEntryActivity.this).edit();
                    editor.putString("phone", userInfo.getUserInfo().getPhone());
                    editor.putString("token", userInfo.getToken());
                    editor.apply();
//                    ToIntent(Constants.PATH_ACTIVITY_MAIN, true);
                    startActivity(new Intent(WXEntryActivity.this, MainActivity.class));
                    EventBus.getDefault().post(new EventBusMessage("startMainActivity"));
                    finish();
                } else if (dataInt.getCode() == 500) {
                    Intent intent = new Intent(WXEntryActivity.this, LoginByCodeActivity.class);
                    intent.putExtra("type", "bindPhone");
                    intent.putExtra("openid",openid);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(WXEntryActivity.this, dataInt.getMessage(), Toast.LENGTH_SHORT).show();
                }
                finish();
            }
        });
    }
}